<?php
namespace control;
// 销售报表
class salesReportFormClass extends adIndexClass
{
	private const page = 'salesReportForm';
	private array $list = [
		'board'       => '数据看板', 'sales_statistics' => '销售统计', 'delivery_rate' => '按期交货率', 'sales_price_fluctuation' => '销售价格波动', 'aging_analysis' => '账龄分析',
		'cost_profit' => '成本与利润', 'customer_contribution_ranking' => '客户贡献排行榜', 'salesperson_ranking' => '销售员排行榜', 'single_sales_ranking' => '单品销售排行榜',
	];
    private const title = '销售报表';
	/*返回网页*/
	public function home()
	{
		$root = root;
        $timeSlot = date("Y-m-d",strtotime("-1 month")).' ~ '.$this->date;
		// 搜索文本框
		$searchTxt =
			"<form name='mainForm' onsubmit='return false'>
                <span class='time_switching' onclick=\"timeSwitching(this,'1')\">今天</span>
                <span class='time_switching' onclick=\"timeSwitching(this,'2')\">昨天</span>
                <span class='time_switching' onclick=\"timeSwitching(this,'3')\">本周</span>
                <span class='time_switching' onclick=\"timeSwitching(this,'4')\">本月</span>" .
                text([
                    'name'    => 'date',
                    'title'   => "时间段",
                    "class"   => "text text-data contour width200",
                    "value"   => $timeSlot,
                    'laydate' => ['range' => '~', 'type' => 'date',],
                ]) .
                "<input class='searchSub' type='button' onclick='cardSearch()' value='查询'>
            </form>";
		//查询最近单品销售排行第一的产品
        $sales_price = find(array(
            "table"=>"sale_order_detail as b join sale_order as a on b.orderId = a.id",
            "field"=>"b.materialId",
            "single"=>" b.coid = '" . self::$coid . "' and a.state = '已确认' order by a.recordDate desc,b.price desc "
        ));
        $materialId = $sales_price['materialId'] ?? '';
		$material        = query("material", " coid = '" . self::$coid . "' and id = '$materialId' ", "name");
		// 搜索文本框
		$price_searchTxt = self::searchText(array(
		    'name' => 'materialName',
            'click' => "search_line('priceFluctuationForm,mainForm','salesReportForm','salesPriceFluctuation')",
            'title' => '产品名称',
            'search' => true,
            'value' => $material['name']
            )) . hidden(array('name' => 'materialId', 'value' => $materialId));
		//$record = query('user_setting',"stid = '".self::$stid."' and type = '销售报表'");
		$setting                       = ["board", "sales_statistics", "delivery_rate", "sales_price_fluctuation", "aging_analysis", "cost_profit", "customer_contribution_ranking", "salesperson_ranking", "single_sales_ranking"];
		$board                         = in_array('board', $setting) ? 'display:block;' : 'display:none;';
		$sales_statistics              = in_array('sales_statistics', $setting) ? 'display:block;' : 'display:none;';
		$delivery_rate                 = in_array('delivery_rate', $setting) ? 'display:block;' : 'display:none;';
		$sales_price_fluctuation       = in_array('sales_price_fluctuation', $setting) ? 'display:block;' : 'display:none;';
		$aging_analysis                = in_array('aging_analysis', $setting) ? 'display:block;' : 'display:none;';
		$cost_profit                   = in_array('cost_profit', $setting) ? 'display:block;' : 'display:none;';
		$customer_contribution_ranking = in_array('customer_contribution_ranking', $setting) ? 'display:block;' : 'display:none;';
		$salesperson_ranking           = in_array('salesperson_ranking', $setting) ? 'display:block;' : 'display:none;';
		$single_sales_ranking          = in_array('single_sales_ranking', $setting) ? 'display:block;' : 'display:none;';

        $cost_tip          = componentClass::tipComponent('毛利润=销售净收入-产品成本-物流分摊运费', '?');
        $profit_rate_tip   = componentClass::tipComponent('毛利率=（销售净收入—产品成本-物流分摊运费）/销售净收入×100%', '?');
		$delivery_rate_tip = componentClass::tipComponent('按期交货率=按期交货订单数（含提前交货）/订单总数', '?');
		$cost_profit_tip   = componentClass::tipComponent("销售成本=产品出库金额-产品退货金额<br>毛利润=销售净收入-产品成本-物流分摊运费<br>毛利率=（销售净收入—产品成本-物流分摊运费）/销售净收入×100%", '?',true);
		$html              = <<<EOT
        <style>
        .time-choice{background-color: #6aacfb!important;color: #eee}
        .data-widget > p{border: none}
        .flex-div > .data-widget:nth-child(2n-1){margin-right: 0}
        .home-warp{flex-direction: column;overflow: auto}
            .title-card-li-content{
              text-align: center;
            }
            .title-card-li-money{
              font-size: 28px;font-weight: bold
            }
            .left-box, .right-box {margin: 0;}
            .left-box{width: 71.5%;}
            .right-box{flex: 1}
            .left-box .flex-div {margin: 0 10px 10px 0;}
            .right-box .flex-div {margin: 0 0 10px 0;}
            .time_switching{
                display: inline-block;
                width: 80px;
                height: 26px;
                line-height: 26px;
                background-color: #e6e6e6;
                text-align: center;
                margin-right: 15px;
                cursor: pointer;
            }
            .text-data{
                margin-right: 15px;
            }
            .m-b-10{margin-bottom: 10px;}
            .revenue{display: flex;align-items: center;}
            .vertical-line{width: 100%;padding-left: 0!important;min-height: 100px;}
            #boardHtml{height: 130px;}
        </style>
        <div class="home-warp">
            <div class="spread-box">
                <div class="search">$searchTxt</div>
                <form name="sortForm">
                    <input type="hidden" name="field" value="">
                    <input type="hidden" name="sort" value="">
                </form>
            </div>
            <div class="box-content">
                <div class="flex-div">
                    <div class="flex-div-children data-widget" style="{$board}">
                        <p><span class="title-card">数据看板</span></p>
                        <ul class="revenue" id="boardHtml">
                            <li class="vertical-line">
                                <div class="title-card-li-content">
                                   <div>销售金额</div>
                                   <div><span class="title-card-li-money">￥0.00</span><span>万</span></div>
                                </div>
                            </li>
                            <li class="vertical-line">
                                <div class="title-card-li-content">
                                   <div>回款金额</div>
                                   <div><span class="title-card-li-money">￥0.00</span><span>万</span></div>
                                </div>
                            </li>
                            <li class="vertical-line">
                                 <div class="title-card-li-content">
                                   <div>毛利润{$cost_tip}</div>
                                   <div><span class="title-card-li-money">￥0.00</span><span>万</span></div>
                                </div>
                            </li>
                            <li class="vertical-line">
                             <div class="title-card-li-content">
                                   <div>毛利率{$profit_rate_tip}</div>
                                   <div><span class="title-card-li-money">0</span><span>%</span></div>
                                </div>
                            </li>
                            <li class="vertical-line">
                             <div class="title-card-li-content">
                                   <div>按期交货率{$delivery_rate_tip}</div>
                                   <div><span class="title-card-li-money">0</span><span>%</span></div>
                                </div>
                            </li>
                        </ul>
                    </div>
                </div>
                <div class="flex-div">
                     <div class="flex-div-children data-widget" style="{$customer_contribution_ranking}">
                       <div class="frame-title"><span class="title-card">客户贡献排行榜</span></div>
                       <div id="customerContributionRankingHtml"></div>
                    </div>
                    <div class="flex-div-children colum-line"></div>
                    <div class="flex-div-children data-widget" style="{$salesperson_ranking}">
                       <div class="frame-title"><span class="title-card">销售员排行榜</span></div>
                       <div id="salespersonRankingHtml"></div>
                    </div>
                </div>
                <div class="flex-div">
                    <div class="flex-div-children data-widget" style="{$single_sales_ranking}">
                       <div class="frame-title"><span class="title-card">单品销售排行榜</span></div>
                       <div id="singleSalesRankingHtml"></div>
                    </div>
                    <div class="flex-div-children colum-line"></div>
                    <div class="flex-div-children data-widget" style="{$sales_statistics}">
                        <p><span class="title-card">销售统计</span></p>
                        <div class="data-box-show" id="salesStatisticsHtml"></div>
                     </div>
                </div>
                <div class="flex-div">
                    <div class="flex-div-children data-widget" style="{$delivery_rate}">
                        <p><span class='title-card'>按期交货率</span></p>
                        <div class="data-box-show" id="deliveryRateHtml"></div>
                    </div>
                    <div class="flex-div-children colum-line">
                    </div>
                    <div class="flex-div-children data-widget" style="{$sales_price_fluctuation}">
                        <form name="priceFluctuationForm" onsubmit='return false'><p><span class='title-card'>销售价格波动</span>{$price_searchTxt}</p></form>
                        <div class="data-box-show" id="salesPriceFluctuationHtml"></div>
                    </div>
                </div>
                 <div class="flex-div">
                    <div class="flex-div-children data-widget" style="{$aging_analysis}">
                        <p><span class="title-card">账龄分布</span></p>
                        <div class="data-box-show" id="agingAnalysisHtml"></div>
                    </div>
                    <div class="flex-div-children colum-line"></div>
                    <div class="flex-div-children data-widget" style="{$cost_profit}">
                        <p><span class='title-card'>成本与利润</span>$cost_profit_tip</p>
                        <div class="data-box-show" id="costProfitHtml"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
     <script src='{$this->root}static/javascript/echarts.min.js'></script>
<script>
function timeSwitching(e,type) {
    $('.time_switching').removeClass('time-choice')
    $(e).addClass('time-choice')
    $.post(root + "control/adIndex.html?cla=salesReportForm&fun=timeSwitching", {type:type}, function (data) {
         $("[name='date']").val(data.date);
         cardSearch();
    }, "json");
}
function search_line(form,cla,fun) {
     $("#" + fun + "Html").html("数据查询中，请稍后。。。");
     //串联表单
        var formName = form.split(",");
        var serialize = "";
        var a = "";
        for (var i = 0; i < formName.length; i++) {
            if (serialize == "") {
                a = "";
            } else {
                a = "&";
            }
            if (formName[i] != "") {
                serialize += a + $("[name=" + formName[i] + "]").serialize();
            }
        }
    $.post(root + "control/adIndex.html?cla=" + cla + "&fun=" + fun, serialize, function (data) {
         $("#" + fun + "Html").html(data.html);
    }, "json");
}
function dataSort(obj) {
    $("[name='field']").val($(obj).data('field'))
    $("[name='sort']").val($(obj).data('sort'))
    search_line('mainForm,sortForm',$(obj).data('cla'),$(obj).data('fun'))
}


/**
* 看板搜索
*/
function cardSearch(){
      ['board', 'salesStatistics', 'deliveryRate', 'salesPriceFluctuation', 'agingAnalysis', 'costProfit', 'customerContributionRanking', 'salespersonRanking', 'singleSalesRanking'].forEach((fun)=>{
                    search_line('mainForm,priceFluctuationForm','salesReportForm', fun)
    })
}

$(function() {
    ['board', 'salesStatistics', 'deliveryRate', 'salesPriceFluctuation', 'agingAnalysis', 'costProfit', 'customerContributionRanking', 'salespersonRanking', 'singleSalesRanking'].forEach((fun)=>{
                    search_line('mainForm,priceFluctuationForm','salesReportForm', fun)
    });
    $("[name='materialName']").each(function (){
          $(this).bigAutocomplete({
            url:root + 'control/adIndex.html?cla=salesReportForm&fun=getMaterial',
            callback:function(data,e){
                e.parent().siblings("input[name='materialId']").val(data.id)
        }})  
    })
})


</script>
EOT;
		$style             = '
        <style>
        .right-box-ul{
            max-height: none;
         }
         .colum-line{width: 10px;flex: 0 0 auto}
         .right-box-title{
            display: flex;
            justify-content: space-around;
         }
         .right-text{
            height: auto;
         }
         .right-box-title li{
            float: left;
            margin: 5px 10px;
            width: 20%;
            text-align: left;
            line-height: 1
         }
         .data-widget-select{
            margin-right: 10px;
         }
         .data-widget-select .fs-label{
             height: 15px;line-height: 15px;
         }
         .data-widget-select .fs-label-wrap{
             border-radius: 4px;
         }
         .aim-rank li{
            margin: 5px 0;
         }
         .aim-rank span{
            display: inline-block;
            width: 100%;
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
            -o-text-overflow:ellipsis;
         }
         /*.aim-rank .right-box-title li:nth-child(1){min-width: 40px}
         .aim-rank .right-box-title li:nth-child(2){width: 100px}
         #singleSalesRankingHtml .right-box-title li:nth-child(2){width: 200px!important;}
         .aim-rank .right-box-title li:nth-child(3){width: 80px}
         .aim-rank .right-box-title li:nth-child(4){width: 80px}*/
</style>';
		return head("ad") . $style . $this->adheader($this->getOnion()) . $html . warn() . $this->adfooter();
	}

	/**
	 * 获取产品数据
	 *
	 * @return bool|string
	 */
	public function getMaterial(): bool|string
	{
		$val          = $this->post('keyword');//关键词
		$json['data'] = [];
		$where        = "";
		if ($val) {
			$where .= " and m.name like '%$val%' ";
		}
		$res = find(array(
		    'field' => " m.id,m.name ",
            'table' => 'material as m',
            'where' => " m.coid = '" . self::$coid . "' " . $where . " order by m.time asc limit 50"
        ));
		foreach ($res['array'] as $val) {
			$json['data'][] = array('title' => $val['name'], 'id' => $val['id']);
		}
		$json['warn'] = 2;
		return json_encode($json, 320);
	}

	/**
	 * 时间选择切换
	 *
	 * @return bool|string
	 */
	public function timeSwitching(): bool|string
	{
		$type = $this->post('type') ?: 1;
		switch ($type) {
			case 2:
				$json['date'] = date('Y-m-d', strtotime("-1 day")) . ' ~ ' . date('Y-m-d', strtotime("-1 day"));
				break;
			case 3:
				$json['date'] = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") - date("w") + 1, date("Y"))) . ' ~ ' . date("Y-m-d", mktime(23, 59, 59, date("m"), date("d") - date("w") + 7, date("Y")));
				break;
			case 4:
				$json['date'] = date("Y-m-01") . ' ~ ' . date("Y-m-t");
				break;
			default:
				$json['date'] = date('Y-m-d') . ' ~ ' . date('Y-m-d');
				break;
		}
		return json_encode($json, 320);
	}

	/**
	 * 显示设置
	 *
	 * @return bool|string
	 */
	public function setting()
	{
		$list    = $this->list;
		$li      = '';
		$index   = 0;
		$setting = query('user_setting', "type='销售报表' and stid = '" . self::$stid . "'");
		$setText = (array)json_decode($setting['value'], true);
		foreach ($list as $id => $name) {
			$index++;
			$checked = '';
			if (in_array($id, $setText)) {
				$checked = 'checked';
			}
			$li .= <<<eof
 <li>
     <div class="li-content"><span class="left">{$name}</span>
         <div class="switch">
              <input id="cmn-toggle-{$index}" name='setting[]' value='{$id}' $checked class="cmn-toggle cmn-toggle-round" type="checkbox">
              <label for="cmn-toggle-{$index}"></label>
        </div>
    </div>
</li>
eof;
		}
		//生成表单
		$html = <<<efo
<form name="settingForm">
<div class="setting-content">
    <ul>
       {$li}
    </ul>
</div>
<div style="width: 100%;text-align: center">
    <button class="button" onclick="subForm('settingForm',root+'control/adIndex.html?cla=salesReportForm&fun=settingEdit')">保存</button>
</div>
</form>
<style>
.li-content{height: 30px;line-height: 30px}
.setting-content>ul{margin: 25px}
.setting-content>ul>li{width: 100%;border-bottom: 1px solid #F2F2F2;padding: 8px 0;}
.switch{display: inline-block;vertical-align: bottom;float: right}
</style>
efo;

		//返回弹出层
		return $this->layer(array("title" => '设置图表展示', "height" => 550, "width" => 400, "html" => $html));
	}

	/**
	 * 图标展示设置
	 *
	 * @return bool|string
	 */
	public function settingEdit(): bool|string
	{
		$setting = $this->post('setting') ?: [];
		$record  = query('user_setting', "type='销售报表' and stid = '" . self::$stid . "'");
		if (!empty($record['id'])) {
			$json['warn'] = static::update(array(
				'table' => 'user_setting',
				'field' => [
					'value' => json_encode($setting, 320),
				],
				'where' => "id = '$record[id]'",
			));
		} else {
			$json['warn'] = static::insert(array(
				'table' => 'user_setting',
				'field' => [
					'stid'  => self::$stid,
					'type'  => '销售报表',
					'value' => json_encode($setting, 320),
				],
			));
		}
		if (in_array($json['warn'], ['新增成功', '更新成功'])) {
			$json['warn'] = 2;
		}
		return json_encode($json, 320);
	}

	/**
	 * 客户贡献排行榜
	 */
	public function customerContributionRanking(): bool|string
	{
		$date  = $this->post('date');
		$field = $this->post('field');
		$sort  = $this->post('sort');
		$where = $aimWhere = '';
		if (!empty($date)) {
			$where    .= $this->timeComparison($date, 'date', 'recordDate');
			$aimWhere .= $this->timeComparison($date, 'date', 'b.recordDate');
		}
		//排序
		$sortArr = ['salesMoney' => 'desc', 'receiptMoney' => 'desc', 'rate' => 'desc'];
		if ($field && in_array($field, array_keys($sortArr))) {
			$order           = " order by $field $sort ";
			$sortArr[$field] = $sort == 'asc' ? 'desc' : 'asc';
		} else {
			$order                 = " order by salesMoney desc ";
			$sortArr['salesMoney'] = 'asc';
		}
		//数据查询
		$sql = find(array(
			"table" => "kehu",
            "field" =>
                "khid,
                (select ifnull(sum(money),0) from sale_order where state = '已确认' and khid = kehu.khid {$where}) as salesMoney,
                (select ifnull(sum(money),0) from receipt_source as a join receipt as b on a.orderId = b.id where b.state = '已确认' and b.classify = 1 and b.targetId = kehu.khid {$aimWhere})+(select ifnull(sum(money),0) from write_off_order_detail as a join write_off_order as b on a.orderId = b.id where b.state = '已确认' and b.type = '预收冲应收' and b.targetId = kehu.khid {$aimWhere}) as receiptMoney,
                if(
                (select ifnull(sum(money),0) from sale_order where state = '已确认' and khid = kehu.khid {$where})>0,
                ((select ifnull(sum(money),0) from receipt_source as a join receipt as b on a.orderId = b.id where b.state = '已确认' and b.classify = 1 and b.targetId = kehu.khid {$aimWhere})+(select ifnull(sum(money),0) from write_off_order_detail as a join write_off_order as b on a.orderId = b.id where b.state = '已确认' and b.type = '预收冲应收' and b.targetId = kehu.khid {$aimWhere}))/(select ifnull(sum(money),0) from sale_order where state = '已确认' and khid = kehu.khid {$where})
                ,0) as rate",
            "where" => " 1=1 and coid = '" . self::$coid . "' $order limit 10",
		));
		//可排序按钮
		$salesMoney   = self::sortButton(['text' => '订单金额', 'sort' => $sortArr['salesMoney'], 'field' => 'salesMoney', 'cla' => 'salesReportForm', 'fun' => 'customerContributionRanking']);
		$receiptMoney = self::sortButton(['text' => '回款金额', 'sort' => $sortArr['receiptMoney'], 'field' => 'receiptMoney', 'cla' => 'salesReportForm', 'fun' => 'customerContributionRanking']);
		$rate         = self::sortButton(['text' => '回款率', 'sort' => $sortArr['rate'], 'field' => 'rate', 'cla' => 'salesReportForm', 'fun' => 'customerContributionRanking']);
		$ul           = '<ul class="right-box-ul aim-rank">';
		if (!$sql['array']) {
			$ul .= '<li class="nodata">暂无内容</li>';
		} else {
			$ul .= "<li><ul class='right-box-title'><li>排名</li><li>客户</li>" . $salesMoney . $receiptMoney . $rate . "</ul></li>";

			foreach ($sql['array'] as $index => $array) {
				$array['rate'] = round($array['rate'], 3) * 100;
				$kehu          = query("kehu", " khid = '$array[khid]' ", "companyName");
				$ul            .= "<li>
                                        <ul class='right-box-title'>
                                            <li>" . ($index + 1) . "</li>
                                            <li>" . zishu($kehu['companyName'], 50) . "</li>
                                            <li>" . ($array['salesMoney'] ?self::lostZero($array['salesMoney']): 0) . "</li>
                                            <li>" . ($array['receiptMoney'] ?self::lostZero($array['receiptMoney']): 0) . "</li>
                                            <li>" . ($array['rate'] ?: 0) . "%</li>
                                        </ul>
                                    </li>";
			}
		}
		$ul .= '</ul>';
		// 拼接字符串
		$json['html'] = $ul;
		return json_encode($json, 320);
	}

	/** 可排序按钮
	 *
	 * @param $data
	 * @return bool|string
	 */
	public static function sortButton($data): bool|string
	{
		$html = "<li data-sort='{$data['sort']}' data-field='{$data['field']}' data-cla='{$data['cla']}' data-fun='{$data['fun']}' onclick=\"dataSort(this)\">{$data['text']}<img style='width: 13px;' src='" . root . "img/svg/sortable.svg'></li>";
		return $html;
	}

	/**,group_concat(distinct id separator \"','\") as ids
	 *销售员排行榜
	 */
	public function salespersonRanking(): bool|string
	{
		$date  = $this->post('date');
		$field = $this->post('field');
		$sort  = $this->post('sort');
		$where = $aimWhere = '';
		if (!empty($date)) {
			$where    .= $this->timeComparison($date, 'date', 'recordDate');
			$aimWhere .= $this->timeComparison($date, 'date', 'b.recordDate');
		}
		//排序
		$sortArr = ['salesMoney' => 'desc', 'receiptMoney' => 'desc', 'rate' => 'desc'];
		if ($field && in_array($field, array_keys($sortArr))) {
			$order           = " order by $field $sort ";
			$sortArr[$field] = $sort == 'asc' ? 'desc' : 'asc';
		} else {
			$order                 = " order by salesMoney desc ";
			$sortArr['salesMoney'] = 'asc';
		}
		//数据查询
		$sql = find(array(
			'field' =>
                "staff.stid,
                saleOrder.money as salesMoney,
                (select sum(money) from receipt_source as a join receipt as b on a.orderId = b.id where b.state = '已确认' and b.classify = 1 and b.targetId in (concat(\"'\",kh.ids,\"'\")) {$aimWhere})+(select sum(money) from write_off_order_detail as a join write_off_order as b on a.orderId = b.id where b.state = '已确认' and b.type = '预收冲应收' and b.targetId in (concat(\"'\",kh.ids,\"'\")) {$aimWhere}) as receiptMoney,
                if(saleOrder.money>0,
                ((select sum(money) from receipt_source as a join receipt as b on a.orderId = b.id where b.state = '已确认' and b.classify = 1 and b.targetId in (concat(\"'\",kh.ids,\"'\")) {$aimWhere})+(select sum(money) from write_off_order_detail as a join write_off_order as b on a.orderId = b.id where b.state = '已确认' and b.type = '预收冲应收' and b.targetId in (concat(\"'\",kh.ids,\"'\")) {$aimWhere}))/saleOrder.money
                ,0) as rate",
            'table' => "staff left join (select IFNULL(sum(money),0) as money,manager,coid from sale_order where state = '已确认' and coid='" . self::$coid . "' {$where} group by manager) as saleOrder on saleOrder.manager = staff.stid left join (select manager,group_concat(distinct khid separator \"','\") as ids from kehu group by manager) as kh on kh.manager = staff.stid",
            'where' => " saleOrder.money > 0 $order limit 10",
		));
		//可排序按钮
		$salesMoney   = self::sortButton(['text' => '订单金额', 'sort' => $sortArr['salesMoney'], 'field' => 'salesMoney', 'cla' => 'salesReportForm', 'fun' => 'salespersonRanking']);
		$receiptMoney = self::sortButton(['text' => '回款金额', 'sort' => $sortArr['receiptMoney'], 'field' => 'receiptMoney', 'cla' => 'salesReportForm', 'fun' => 'salespersonRanking']);
		$rate         = self::sortButton(['text' => '回款率', 'sort' => $sortArr['rate'], 'field' => 'rate', 'cla' => 'salesReportForm', 'fun' => 'salespersonRanking']);
		$ul           = '<ul class="right-box-ul aim-rank">';
		if (!$sql['array']) {
			$ul .= '<li class="nodata">暂无内容</li>';
		} else {
			$ul .= "<li><ul class='right-box-title'><li>排名</li><li>员工</li>{$salesMoney}{$receiptMoney}{$rate}</ul></li>";

			foreach ($sql['array'] as $index => $array) {
				$array['rate'] = round($array['rate'], 3) * 100;
				$ul            .= "<li><ul class='right-box-title'><li>" . ($index + 1) . "</li><li>" . zishu(self::findStaff($array['stid']), 50) . "</li><li>" . ($array['salesMoney'] ?self::lostZero($array['salesMoney']): 0) . "</li><li>" . ($array['receiptMoney'] ?self::lostZero($array['receiptMoney']): 0) . "</li><li>" . ($array['rate'] ?: 0) . "%</li></ul></li>";
			}
		}
		$ul .= '</ul>';
		// 拼接字符串
		$json['html'] = $ul;
		return json_encode($json, 320);
	}

	/**
	 *单品销售排行榜
	 */
	public function singleSalesRanking(): bool|string
	{
		$date  = $this->post('date');
		$field = $this->post('field');
		$sort  = $this->post('sort');
		$where = " and b.state = '已确认' ";
		if (!empty($date)) {
			$where .= $this->timeComparison($date, 'date', 'b.recordDate');
		}
		//排序
		$sortArr = ['num' => 'desc', 'money' => 'desc'];
		if ($field && in_array($field, array_keys($sortArr))) {
			$order           = " order by $field $sort ";
			$sortArr[$field] = $sort == 'asc' ? 'desc' : 'asc';
		} else {
			$order          = " order by num desc ";
			$sortArr['num'] = 'asc';
		}
		//数据查询
		$sql = find(array(
		    "table" => "sale_order_detail as a join sale_order as b on a.orderId = b.id",
            "field" => " a.materialId,any_value(IFNULL(sum(a.money),0)) as money,any_value(IFNULL(sum(a.num),0)) as num ",
            "where" => " 1=1 and a.coid = '" . self::$coid . "' {$where} group by a.materialId {$order} limit 10"
        ));
		//可排序按钮
		$num   = self::sortButton(['text' => '销售数量', 'sort' => $sortArr['num'], 'field' => 'num', 'cla' => 'salesReportForm', 'fun' => 'singleSalesRanking']);
		$money = self::sortButton(['text' => '销售金额', 'sort' => $sortArr['money'], 'field' => 'money', 'cla' => 'salesReportForm', 'fun' => 'singleSalesRanking']);
		$ul    = '<ul class="right-box-ul aim-rank">';
		if (!$sql['array']) {
			$ul .= '<li class="nodata">暂无内容</li>';
		} else {
			$ul .= "<li><ul class='right-box-title'><li>排名</li><li>产品名称</li>{$num}{$money}</ul></li>";

			foreach ($sql['array'] as $index => $array) {
				$material = query("material", " id = '$array[materialId]' ", "name");
				$ul       .= "
                            <li>
                                <ul class='right-box-title'>
                                    <li>" . ($index + 1) . "</li>
                                    <li>" . zishu($material['name'],50) . "</li>
                                    <li>" . ($array['num'] ?self::lostZero($array['num'],'numPrecision'): 0) . "</li>
                                    <li>" . ($array['money'] ?self::lostZero($array['money']): 0) . "</li>
                                </ul>
                            </li>";
			}
		}
		$ul .= '</ul>';
		// 拼接字符串
		$json['html'] = $ul;
		return json_encode($json, 320);
	}

	/**
	 * 销售统计
	 *
	 * @return bool|string
	 */
	public function salesStatistics(): bool|string
	{
		$date = $this->post('date');
		if (!empty($date)) {
			$timeArr = explode(' ~ ', $date);
		} else {
			$timeArr[0] = date('Y-m-d', strtotime("-14 day"));
			$timeArr[1] = $this->date;
		}
		$m   = $timeArr[0];
		$res = [];
		while ($m <= $timeArr[1]) {
			$amountReceivable = find(array(
			    'table' => 'record',
                'where' => " coid = '" . self::$coid . "' and classify = '销售发货' and targetDate = '$m' ",
                'sum' => "money"
            ));
			$amountCollected = (float)find(array(
			    'table' => "receipt_source as a join receipt as b on a.orderId = b.id",
                "single" => " coid = '" . self::$coid . "' and b.state = '已确认' and b.classify = 1 and b.recordDate = '$m' ",
                'sum' => "money"
            ));
			//核销单
			$amountCollected += (float)find(array(
			    'table' => "write_off_order_detail as a join write_off_order as b on a.orderId = b.id",
                "single" => " coid = '" . self::$coid . "' and b.state = '已确认' and b.recordDate = '$m' and b.type = '预收冲应收' ",
                'sum' => "money"
            ));
			$res[]           = [
				'date'             => date("m月d日", strtotime($m)),
				'amountReceivable' => round($amountReceivable / 10000, 2),
				'amountCollected'  => round($amountCollected / 10000, 2),
			];
			$m               = date("Y-m-d", strtotime($m . " +1 day"));
		}
		$data         = [
			"subtext" => '单位：万元',
			"name"    => array_column($res, 'date'),
			"series"  => [
				[
					'name' => '应收金额',
					'data' => array_column($res, 'amountReceivable'),
				],
				[
					'name' => '收款金额',
					'data' => array_column($res, 'amountCollected'),
				],
			],
		];
		$json['html'] = $this->curve($data, 'area');
		return json_encode($json, 320);
	}

	/**
	 * 按期交货率
	 *
	 * @return bool|string
	 */
	public function deliveryRate(): bool|string
	{
		$date = $this->post('date');
		if (!empty($date)) {
			$timeArr = explode(' ~ ', $date);
		} else {
			$timeArr[0] = date('Y-m-d', strtotime("-6 day"));
			$timeArr[1] = $this->date;
		}
		$m   = $timeArr[0];
		$res = [];
        $totalOnScheduleNum = 0;
		while ($m <= $timeArr[1]) {
			//按期交货率
			$orderNum             = find([
				'table'  => "sale_order",
				'field'  => "IFNULL(count(id),0) as num",
				'single' => " coid = '" . self::$coid . "' and state = '已确认' and recordDate = '$m' ",
			])['num'] ?? 0;
			$onScheduleNum        = find([
				'table'  => "sale_order",
				'field'  => "IFNULL(count(id),0) as num",
				'single' => " coid = '" . self::$coid . "' and state = '已确认' and recordDate = '$m' and deliver_on_schedule = 1 ",
			])['num'] ?? 0;
			$delayNum             = find([
				'table'  => "sale_order",
				'field'  => "IFNULL(count(id),0) as num",
				'single' => " coid = '" . self::$coid . "' and state = '已确认' and recordDate = '$m' and ((deliver_on_schedule = 0 and unix_timestamp(curdate()) > unix_timestamp(deliveryDate)) or deliver_on_schedule = 2)  ",
			])['num'] ?? 0;
			$scheduleDeliveryRate = ($orderNum > 0 ? round(($onScheduleNum / $orderNum) * 100, 1) : 0);
			$res[]                = [
				'date'                 => date("m月d日", strtotime($m)),
				'onScheduleNum'        => $onScheduleNum,
				'delayNum'             => $delayNum,
				'scheduleDeliveryRate' => $scheduleDeliveryRate,
			];
            $totalOnScheduleNum += $onScheduleNum;
			$m                    = date("Y-m-d", strtotime($m . " +1 day"));
		}
		$data         = [
			"graphic"   => "按期交货订单总数量：".$totalOnScheduleNum,
			"name"   => array_column($res, 'date'),
			"series" => [
				[
					'name'     => '按期交货订单笔数',
					'stack'    => 'num',
					'emphasis' => json_encode(['focus' => 'series']),
					'data'     => array_column($res, 'onScheduleNum'),
				],
				[
					'name'     => '延期交货订单笔数',
					'stack'    => 'num',
					'emphasis' => json_encode(['focus' => 'series']),
					'data'     => array_column($res, 'delayNum'),
				],
				[
					'name' => '按期交货率',
					'type' => 'line',
					'data' => array_column($res, 'scheduleDeliveryRate'),
				],
			],
		];
		$json['html'] = $this->curve($data, 'bar');
		return json_encode($json, 320);
	}

	/**
	 * 成本与利润
	 *
	 * @return bool|string
	 */
	public function costProfit(): bool|string
	{
		$date = $this->post('date');
		if (!empty($date)) {
			$timeArr = explode(' ~ ', $date);
		} else {
			$timeArr[0] = date('Y-m-d', strtotime("-6 day"));
			$timeArr[1] = $this->date;
		}
		$m   = $timeArr[0];
		$res = [];
		while ($m <= $timeArr[1]) {
			//毛利润
            //发货出库金额
            $out_cost_money = find(array(
                "table"=>" inventory_changes_detail as detail join inventory_changes as main on detail.orderId = main.id join inventory_detail as mx on mx.id = detail.sourceId ",
                "field"=>" ifnull(sum(detail.money),0) as money ",
                "single"=>" main.state in ('已出库','已复核') and main.coid = '".self::$coid."' and mx.sourceTable = 'sale_send_order_detail' and main.recordDate = '$m' "
            ))['money'];
            //退货入库金额
            $in_cost_money = find(array(
                "table"=>" inventory_changes_detail as detail join inventory_changes as main on detail.orderId = main.id join inventory_detail as mx on mx.id = detail.sourceId ",
                "field"=>" ifnull(sum(detail.money),0) as money ",
                "single"=>" main.state in ('已入库','已复核') and main.coid = '".self::$coid."' and mx.sourceTable = 'sale_refund_order_detail' and main.recordDate = '$m' "
            ))['money'];
            $cost   = self::formattingFigure($out_cost_money - $in_cost_money);
            //销售发货金额
            $out_Money = find(array(
                "table"=>" inventory_detail as detail join inventory as main on detail.orderId = main.id ",
                "field"=>" ifnull(sum(detail.money),0) as money ",
                "single"=>" detail.coid = '" . self::$coid . "' and detail.sourceTable = 'sale_send_order_detail' and main.sourceDate = '$m' "
            ))['money'];
            //退货金额
            $refund_Money = find(array(
                "table"=>" inventory_detail as detail join inventory as main on detail.orderId = main.id ",
                "field"=>" ifnull(sum(detail.money),0) as money ",
                "single"=>" detail.coid = '" . self::$coid . "' and detail.sourceTable = 'sale_refund_order_detail' and main.sourceDate = '$m' "
            ))['money'];
            $income = round($out_Money - $refund_Money, 2);  //收入
            //分摊运费
            $freightMoney = find(array(
                "table"=>" sale_send_order_loading as loading join sale_send_order as ord on loading.orderId = ord.id ",
                "field"=>" ifnull(sum(loading.freight),0) as freight ",
                "single"=>" ord.coid = '".self::$coid."' and ord.state = '已确认' and ord.recordDate = '$m' "
            ))['freight'];

			$grossProfit = round($income - $cost - $freightMoney, 2);
			//毛利率
			$grossProfitRate = ($income > 0 ? round((($income - $cost - $freightMoney) / $income) * 100, 1) : 0);
			$res[]           = [
				'date'            => date("m月d日", strtotime($m)),
				'cost'            => $cost,
				'grossProfit'     => $grossProfit,
				'grossProfitRate' => $grossProfitRate,
			];
			$m               = date("Y-m-d", strtotime($m . " +1 day"));
		}
		$data         = [
			"name"   => array_column($res, 'date'),
			"series" => [
				[
					'name'     => '销售成本',
					'stack'    => 'money',
					'emphasis' => json_encode(['focus' => 'series']),
					'data'     => array_column($res, 'cost'),
				],
				[
					'name'     => '毛利润',
					'stack'    => 'money',
					'emphasis' => json_encode(['focus' => 'series']),
					'data'     => array_column($res, 'grossProfit'),
				],
				[
					'name' => '毛利率',
					'type' => 'line',
					'data' => array_column($res, 'grossProfitRate'),
				],
			],
		];
		$json['html'] = $this->curve($data, 'bar');
		return json_encode($json, 320);
	}

	/**
	 * 销售价格波动 数据
	 */
	public function salesPriceFluctuation(): bool|string
	{
		$date          = $this->post('date');
		$materialId = $this->post('materialId');

		if (!empty($date)) {
			$timeArr = explode(' ~ ', $date);
		} else {
			$timeArr[0] = date('Y-m-d', strtotime("-6 day"));
			$timeArr[1] = $this->date;
		}
		if (empty($materialId)) {
			//查询最近单品销售排行第一的产品
            $sales_price = find(array(
                "table"=>"sale_order_detail as b join sale_order as a on b.orderId = a.id",
                "field"=>"b.materialId",
                "single"=>" b.coid = '" . self::$coid . "' and a.state = '已确认' order by a.recordDate desc,b.price desc "
            ));
            $materialId = isset($sales_price['materialId'])?$sales_price['materialId']:'';
		}
		$where = " and b.materialId = '$materialId' ";
		$m     = $timeArr[0];
		$res   = [];
		while ($m <= $timeArr[1]) {
            $sales_price = find(array(
                "table"=>"sale_order_detail as b join sale_order as a on b.orderId = a.id",
                "field"=>"b.price",
                "single"=>" b.coid = '" . self::$coid . "' and a.state = '已确认' and date_format(a.recordDate, '%Y-%m-%d') = '$m' {$where} order by b.price desc "
            ));
			$price = isset($sales_price['price']) ?$sales_price['price']: 0;
			$res[] = [
				'date'  => date("m月d日", strtotime($m)),
				'price' => $price,
			];
			$m     = date("Y-m-d", strtotime($m . " +1 day"));
		}
		$data         = [
			"name"   => array_column($res, 'date'),
			"series" => [
				[
					'name' => '',
					'data' => array_column($res, 'price'),
				],
			],
		];
		$json['html'] = $this->curve($data);
		return json_encode($json, 320);
	}

	/**
	 * 账龄分布 - 返回数据
	 */
	public function agingAnalysis(): bool|string
	{
		$arr = ['未到期', '0-30天', '30-60天', '60-90天', '90天以上'];
		$res = [];
		foreach ($arr as $index => $text) {
			$where = "";
			switch ($index) {
				case 0:
					$where = " and now() <= date_add(send.recordDate, interval send.settlementDay day) ";
					break;
				case 1:
					$where = " and datediff('{$this->date}',date_add(send.recordDate, interval send.settlementDay day)) > 0 and datediff('{$this->date}',date_add(send.recordDate, interval send.settlementDay day)) <= 30 ";
					break;
				case 2:
					$where = " and datediff('{$this->date}',date_add(send.recordDate, interval send.settlementDay day)) > 30 and datediff('{$this->date}',date_add(send.recordDate, interval send.settlementDay day)) <= 60 ";
					break;
				case 3:
					$where = " and datediff('{$this->date}',date_add(send.recordDate, interval send.settlementDay day)) > 60 and datediff('{$this->date}',date_add(send.recordDate, interval send.settlementDay day)) <= 90 ";
					break;
				case 4:
					$where = " and datediff('{$this->date}',date_add(send.recordDate, interval send.settlementDay day)) > 90 ";
					break;
			}
			$result   = find(array(
				'field' => "send.id,send.time,(receivable.money - (IFNULL(receipt.money,0)+IFNULL(writeOff.money,0))) as surplus",
                'table' => "sale_send_order as send left join
     (select IFNULL(sum(i.money),0) as money,detail.orderId from sale_send_order_detail as detail join inventory_detail as i on detail.id =i.sourceId group by detail.orderId) as receivable on receivable.orderId = send.id left join
     (select IFNULL(sum(abs(a.money)),0) as money,a.sourceId from receipt_source as a join receipt as b on a.orderId = b.id where b.state = '已确认' group by a.sourceId) as receipt on receipt.sourceId = send.id left join
     (select IFNULL(sum(abs(a.money)),0) as money,a.sourceId from write_off_order_detail as a join write_off_order as b on a.orderId = b.id where b.state = '已确认' group by a.sourceId) as writeOff on writeOff.sourceId = send.id",
                'where' => " send.coid='" . self::$coid . "' and send.state = '已确认' and receivable.money > 0 and IFNULL(receipt.money,0)+IFNULL(writeOff.money,0) < receivable.money " . $where,
			));
			$moneyArr = (array)array_column($result['array'], 'surplus');
			$res[]    = [
				'text'  => $text,
				'money' => round(array_sum($moneyArr) / 10000, 2),
			];
		}
		$data         = [
			"subtext" => '单位：万元',
			"name"    => array_column($res, 'text'),
			"series"  => [
				[
					'name' => '剩余应收金额',
					'data' => array_column($res, 'money'),
				],
			],
		];
		$json['html'] = $this->barCharts($data);
		return json_encode($json, 320);
	}


	/**
	 * 数据看板
	 */
	public function board(): bool|string
	{
        $root = $this->root;
		$cost_tip          = componentClass::tipComponent('毛利润=销售净收入-产品成本-物流分摊运费', '?');
		$profit_rate_tip   = componentClass::tipComponent('毛利率=（销售净收入-产品成本-物流分摊运费）/销售净收入×100%', '?');
		$delivery_rate_tip = componentClass::tipComponent('按期交货率=按期交货订单数（含提前交货）/订单总数', '?');
		$date              = $this->post('date');
		$json['html']      = '';
		//销售金额
		$where = " and coid = '" . self::$coid . "' ";
		if ($date) {
			$where .= $this->timeComparison($date, 'date', 'recordDate');
		}
		$saleMoney    = find(array(
		    'table' => 'sale_order',
            'where' => "state = '已确认'" . $where,
            'sum' => "money"
        ));
        $money = self::convertToTenThousand($saleMoney);
		$json['html'] .= <<<efo
                        <li class="quarter left vertical-line no-hover">
                            <div class="title-card-li-content">
                               <div>销售金额</div>
                                <div><span class="title-card-li-money">￥{$money['amount']}</span><span>{$money['unit']}</span></div>
                            </div>
                        </li>
         
efo;
		//回款金额
		$where = " and b.coid = '" . self::$coid . "' ";
		if ($date) {
			$where .= $this->timeComparison($date, 'date', 'b.recordDate');
		}
		$backMoney = find(array(
		    'table' => "receipt_source as a join receipt as b on a.orderId = b.id",
            "single" => " b.state = '已确认' and b.classify = 1 " . $where,
            'sum' => "money"
        ));
		//核销单
		$backMoney    += find(array(
		    'table' => "write_off_order_detail as a join write_off_order as b on a.orderId = b.id",
            "single" => " b.state = '已确认' and b.type = '预收冲应收' " . $where,
            'sum' => "money"
        ));
        $money = self::convertToTenThousand($backMoney);
		$json['html'] .= <<<efo
                        <li class="vertical-line no-hover">
                            <div class="title-card-li-content">
                                <div>回款金额</div>
                                <div><span class="title-card-li-money">￥{$money['amount']}</span><span>{$money['unit']}</span></div>
                            </div>
                        </li>
         
efo;
		//毛利润
		/*$whereSale = $whereInventory = $whereFreight = "";
		if ($date) {
            $whereSale .= $this->timeComparison($date, 'date', 'main.recordDate');
            $whereInventory .= $this->timeComparison($date, 'date', 'main.sourceDate');
            $whereFreight .= $this->timeComparison($date, 'date', 'ord.recordDate');
		}
        //发货出库金额
        $out_cost_money = find(array(
            "table"=>" inventory_changes_detail as detail join inventory_changes as main on detail.orderId = main.id join inventory_detail as mx on mx.id = detail.sourceId ",
            "field"=>" ifnull(sum(detail.money),0) as money ",
            "single"=>" main.state in ('已出库','已复核') and main.coid = '".self::$coid."' and mx.sourceTable = 'sale_send_order_detail' {$whereSale} "
        ))['money'];
        //退货入库金额
        $in_cost_money = find(array(
            "table"=>" inventory_changes_detail as detail join inventory_changes as main on detail.orderId = main.id join inventory_detail as mx on mx.id = detail.sourceId ",
            "field"=>" ifnull(sum(detail.money),0) as money ",
            "single"=>" main.state in ('已入库','已复核') and main.coid = '".self::$coid."' and mx.sourceTable = 'sale_refund_order_detail' {$whereSale} "
        ))['money'];
        $cost   = self::formattingFigure($out_cost_money - $in_cost_money);
        //销售发货金额
        $out_Money = find(array(
            "table"=>" inventory_detail as detail join inventory as main on detail.orderId = main.id ",
            "field"=>" ifnull(sum(detail.money),0) as money ",
            "single"=>" detail.coid = '" . self::$coid . "' and detail.sourceTable = 'sale_send_order_detail' {$whereInventory} "
        ))['money'];
        //退货金额
        $refund_Money = find(array(
            "table"=>" inventory_detail as detail join inventory as main on detail.orderId = main.id ",
            "field"=>" ifnull(sum(detail.money),0) as money ",
            "single"=>" detail.coid = '" . self::$coid . "' and detail.sourceTable = 'sale_refund_order_detail' {$whereInventory} "
        ))['money'];
        $income = round($out_Money - $refund_Money, 2);  //收入
        //分摊运费
        $freightMoney = find(array(
            "table"=>" sale_send_order_loading as loading join sale_send_order as ord on loading.orderId = ord.id ",
            "field"=>" ifnull(sum(loading.freight),0) as freight ",
            "single"=>" ord.coid = '".self::$coid."' and ord.state = '已确认' {$whereFreight} "
        ))['freight'];*/

        $whereSale = "";
        if ($date) {
            $whereSale .= $this->timeComparison($date, 'date', 'recordDate');
        }
        //统计
        $totalSql = find(array(
            "table"=>" sale_order_detail as a join sale_order as b on a.orderId = b.id join material as c on c.id = a.materialId ",
            "field"=>" a.id ",
            "where"=>" a.coid = '".self::$coid."' and b.state = '已确认' {$whereSale} "
        ));
        $ids = implode("','",(array)array_column($totalSql['array'],'id'));
        //发货出库金额
        $out_cost = find(array(
            "table"=>" inventory_changes_detail as detail join inventory_changes as main on detail.orderId = main.id join inventory_detail as mx on mx.id = detail.sourceId ",
            "field"=>" ifnull(sum(detail.num),0) as num,ifnull(sum(detail.money),0) as money ",
            "single"=>" main.state in ('已出库','已复核') and main.coid = '".self::$coid."' and mx.sourceTable = 'sale_send_order_detail' and mx.sourceId in (select id from sale_send_order_detail where saleOrderMxId in ('$ids')) "
        ));
        //退货入库金额
        $in_cost = find(array(
            "table"=>" inventory_changes_detail as detail join inventory_changes as main on detail.orderId = main.id join inventory_detail as mx on mx.id = detail.sourceId ",
            "field"=>" ifnull(sum(detail.num),0) as num,ifnull(sum(detail.money),0) as money ",
            "single"=>" main.state in ('已入库','已复核') and main.coid = '".self::$coid."' and mx.sourceTable = 'sale_refund_order_detail' and mx.sourceId in (select id from sale_refund_order_detail where sourceId  in ('$ids')) "
        ));
        $cost   = self::formattingFigure($out_cost['money'] - $in_cost['money']);
        //销售发货金额
        $out_Money = find(array(
            "table"=>" inventory_detail as detail join inventory as main on detail.orderId = main.id ",
            "field"=>" ifnull(sum(detail.money),0) as money ",
            "single"=>" detail.coid = '" . self::$coid . "' and detail.sourceTable = 'sale_send_order_detail' and detail.sourceId in (select id from sale_send_order_detail where saleOrderMxId  in ('$ids')) "
        ))['money'];
        //退货金额
        $refund_Money = find(array(
            "table"=>" inventory_detail as detail join inventory as main on detail.orderId = main.id ",
            "field"=>" ifnull(sum(detail.money),0) as money ",
            "single"=>" detail.coid = '" . self::$coid . "' and detail.sourceTable = 'sale_refund_order_detail' and detail.sourceId in (select id from sale_refund_order_detail where sourceId  in ('$ids')) "
        ))['money'];
        $income = round($out_Money - $refund_Money, 2);  //收入
        //分摊运费
        $freightMoney = find(array(
            "table"=>" sale_send_order_loading as loading join sale_send_order as ord on loading.orderId = ord.id ",
            "field"=>" ifnull(sum(loading.freight),0) as freight ",
            "single"=>" ord.coid = '".self::$coid."' and ord.state = '已确认' and loading.saleOrderMxId in ('$ids') "
        ))['freight'];
		$grossProfit  = round($income - $cost - $freightMoney, 2);
		//毛利率
		$grossProfitRate = ($income > 0 ? round((($income - $cost - $freightMoney) / $income) * 100, 1) : 0);

        $money = self::convertToTenThousand($grossProfit);
		$json['html'] .= <<<efo
                        <li class="vertical-line" onclick="newIframe('销售利润表','{$root}control/adIndex.html?cla=saleProfit&fun=home')">
                            <div class="title-card-li-content">
                                <div>毛利润{$cost_tip}</div>
                                <div><span class="title-card-li-money">￥{$money['amount']}</span><span>{$money['unit']}</span></div>
                            </div>
                        </li>
         
efo;

		$json['html']    .= <<<efo
                        <li class="vertical-line" onclick="newIframe('销售利润表','{$root}control/adIndex.html?cla=saleProfit&fun=home')">
                            <div class="title-card-li-content">
                                <div>毛利率{$profit_rate_tip}</div>
                                <div><span class="title-card-li-money">{$grossProfitRate}</span><span>%</span></div>
                            </div>
                        </li>
         
efo;
		//按期交货率
		$where = "";
		if ($date) {
			$where .= $this->timeComparison($date, 'date', 'recordDate');
		}
		$orderNum             = find([
			'table'  => "sale_order",
			'field'  => "IFNULL(count(id),0) as num",
			'single' => " coid = '" . self::$coid . "' and state = '已确认' " . $where,
		])['num'] ?? 0;
		$onScheduleNum        = find([
			'table'  => "sale_order",
			'field'  => "IFNULL(count(id),0) as num",
			'single' => " coid = '" . self::$coid . "' and state = '已确认' and deliver_on_schedule = 1 " . $where,
		])['num'] ?? 0;
		$scheduleDeliveryRate = ($orderNum > 0 ? round(($onScheduleNum / $orderNum) * 100, 1) : 0);
		$json['html']         .= <<<efo
                        <li class="vertical-line no-hover">
                            <div class="title-card-li-content">
                                <div>按期交货率{$delivery_rate_tip}</div>
                                <div><span class="title-card-li-money">{$scheduleDeliveryRate}</span><span>%</span></div>
                            </div>
                        </li>
         
efo;
		return json_encode($json, 320);
	}


	/**
	 * 桌面数据看板
	 */
	public function boardHome(): bool|string
	{
		$date         = $this->post('date');
		$json['html'] = '';
		//销售金额
		$where = " and coid = '" . self::$coid . "' ";
		if ($date) {
			$where .= $this->timeComparison($date, 'date', 'recordDate');
		}
		$saleMoney    = find(array(
		    'table' => 'sale_order',
            'where' => "state = '已确认'" . $where,
            'sum' => "money"
        ));
		$text         = $saleMoney > 10000 ? '万' : '';
		$money        = round($saleMoney > 10000 ? ($saleMoney / 10000) : $saleMoney, 2);
		$json['html'] .= <<<efo
                        <li class="quarter left vertical-line">
                            <div class="title-card-li-content">
                               <div>销售金额</div>
                                <div><span class="title-card-li-money">￥{$money}</span><span>{$text}</span></div>
                            </div>
                        </li>
         
efo;
		//回款金额
		$where = " and b.coid = '" . self::$coid . "' ";
		if ($date) {
			$where .= $this->timeComparison($date, 'date', 'b.recordDate');
		}
		$backMoney = find(array(
		    'table' => "receipt_source as a join receipt as b on a.orderId = b.id",
            "single" => " b.state = '已确认' and b.classify = 1 " . $where,
            'sum' => "money"
        ));
		//核销单
		$backMoney    += find(array(
		    'table' => "write_off_order_detail as a join write_off_order as b on a.orderId = b.id",
            "single" => " b.state = '已确认' and b.type = '预收冲应收' " . $where,
            'sum' => "money"
        ));
		$text         = $backMoney > 10000 ? '万' : '';
		$money        = $backMoney > 10000 ? round(($backMoney / 10000), 2) : round($backMoney, 2);
		$json['html'] .= <<<efo
                        <li class="quarter left vertical-line">
                            <div class="title-card-li-content">
                                <div>回款金额</div>
                                <div><span class="title-card-li-money">￥{$money}</span><span>{$text}</span></div>
                            </div>
                        </li>
         
efo;
		//采购金额
		$where = " and coid = '" . self::$coid . "' ";
		if ($date) {
			$where .= $this->timeComparison($date, 'date', 'recordDate');
		}
		$purchaseMoney = find(array(
		    'table' => 'purchase_order',
            'where' => "state = '已确认'" . $where,
            'sum' => "money"
        ));
		$text          = $purchaseMoney > 10000 ? '万' : '';
		$money         = round($purchaseMoney > 10000 ? ($purchaseMoney / 10000) : $purchaseMoney, 2);
		$json['html']  .= <<<efo
                        <li class="quarter left vertical-line">
                            <div class="title-card-li-content">
                               <div>材料采购金额</div>
                                <div><span class="title-card-li-money">￥{$money}</span><span>{$text}</span></div>
                            </div>
                        </li>
         
efo;
		if (!empty($date)) {
			$timeArr = explode(' ~ ', $date);
		} else {
			$timeArr[0] = $this->date;
			$timeArr[1] = $this->date;
		}
		//期末库存金额
		$inventory         = find(array(
		    'field' => " materialId,any_value(ifnull(sum(num),0)) as num ",
            'table' => 'inventory_record',
            'where' => " coid = '" . self::$coid . "' and date_format(time, '%Y-%m-%d') <= '$timeArr[1]' group by materialId having sum(num) > 0 "));
        $terminalInventory = 0;
		foreach ((array)$inventory['array'] as $array){
		    $avgPrice = inventoryDefaultClass::lostZero($array['materialId'],'',$timeArr[1]);
            $terminalInventory += self::formattingFigure($array['num']*$avgPrice);
        }

		$text              = $terminalInventory > 10000 ? '万' : '';
		$money             = round($terminalInventory > 10000 ? ($terminalInventory / 10000) : $terminalInventory, 2);
		$json['html']      .= <<<efo
                        <li class="quarter left vertical-line">
                            <div class="title-card-li-content">
                                <div>库存金额</div>
                                <div><span class="title-card-li-money">{$money}</span><span>{$text}</span></div>
                            </div>
                        </li>
         
efo;

		return json_encode($json, 320);
	}

}
